<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { cloneDeep } from '@vben/utils';

import { Modal } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { productList } from '#/api/hm/product';
import { saleOrderInfo } from '#/api/hm/saleOrder';
import {
  saleOrderPickUpAdd,
  saleOrderPickUpUpdate,
} from '#/api/hm/saleOrderPickUp';

import { modalSchema } from './data';

const emit = defineEmits<{ reload: [] }>();

const isUpdate = ref(false);
const title = computed(() => {
  return '业务处理';
});

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    // 默认占满两列
    formItemClass: 'col-span-2',
    // 默认label宽度 px
    labelWidth: 80,
    // 通用配置项 会影响到所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  schema: modalSchema(),
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2',
});

const [BasicModal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel: handleCancel,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    modalApi.modalLoading(true);

    const { saleOrderId, isGift } = modalApi.getData() as {
      isGift?: string;
      saleOrderId?: number | string;
    };
    isUpdate.value = false;

    const record = await saleOrderInfo(saleOrderId);
    const info = {
      saleProductId: record.saleProductId, // 销售产品id
      saleProductName: record.saleProductName, // 销售产品名称
      saleOrderId: record.saleId, // 销售订单id
      isGift: record.isGift, // 是否赠品
      giftList: [] as { label: any; value: any }[], // 赠品集合
      maxPickUpNum: record.saleNum - record.returnTotalNum, // 可退数量,
      maxRefundAmount: record.saleAmount - record.refundAmount, // 可退金额
      maxRefundSurplusNum: record.refundSurplusNum, // 剩余未回款金额
      maxSurplusNum: record.surplusNum, // 剩余未提数量
    };
    // 更新赠品schema
    if (isGift === 'Y') {
      const dataSourceOptions = [];
      const transOptions = record.giftList?.map((item) => ({
        label: item.giftProductName,
        value: item.giftProductId.toString(),
        maxQty: item.giftNum - item.giftRefundableNum, // 可退数量
        maxExtractQty:
          item.giftNum - item.giftUsedNum === 0
            ? 0
            : item.giftNum - item.giftRefundableNum - item.giftUsedNum, // 可提取数量
      }));
      if (transOptions) {
        dataSourceOptions.push(...transOptions);
      }
      formApi.updateSchema([
        {
          fieldName: 'giftProductId',
          componentProps: {
            options: dataSourceOptions,
          },
        },
      ]);
      info.giftList = dataSourceOptions;
    }
    console.log('info', info);
    await formApi.setValues(info);
    modalApi.modalLoading(false);
  },
});

async function handleConfirm() {
  try {
    modalApi.modalLoading(true);
    const { valid } = await formApi.validate();
    if (!valid) return;

    Modal.confirm({
      title: '提示',
      okType: 'danger',
      content: `请核对信息是否正确，确定提交吗？`,
      onOk: async () => {
        const data = cloneDeep(await formApi.getValues());
        data.giftReturns = data.giftReturns?.filter(
          (item: any) => item.selected,
        );
        if (
          data.pickUpType === 0 && // 回款校验
          data.pickUpAmount > data.maxRefundSurplusNum
        ) {
          Modal.error({
            title: '提示',
            content: `回款金额不能大于最大可回款金额${data.maxRefundSurplusNum}`,
          });
          return; // 增加错误处理后的阻断
        }
        if (data.pickUpType === 1) {
          if (data.pickUpNum === 0) {
            Modal.error({ title: '提示', content: '提货数量不能为0' });
            return; // 增加 return 阻止继续执行
          }
          // 提货校验
          if (data.pickUpNum > data.maxPickUpNum) {
            Modal.error({
              title: '提示',
              content: `提货数量不能大于可退数量${data.maxPickUpNum}`,
            });
            return; // 增加错误处理后的阻断
          }
        }
        await (isUpdate.value
          ? saleOrderPickUpUpdate(data)
          : saleOrderPickUpAdd(data));
        emit('reload');
        await handleCancel();
      },
    });
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.modalLoading(false);
  }
}

async function handleCancel() {
  modalApi.close();
  await formApi.resetForm();
}
// 商品集合Schema 更新
onMounted(async () => {
  const ret = await productList({
    pageNum: 1,
    pageSize: 999,
    status: '0',
    productType: 'CP',
  });
  const dataSourceOptions = [];
  const transOptions = ret.rows.map((item) => ({
    label: item.productName,
    value: item.productId.toString(),
  }));
  dataSourceOptions.push(...transOptions);
  formApi.updateSchema([
    {
      fieldName: 'productId',
      componentProps: {
        options: dataSourceOptions,
        allowClear: true,
        showSearch: true,
        optionFilterProp: 'label',
      },
    },
  ]);
});
</script>

<template>
  <BasicModal :close-on-click-modal="false" :title="title" class="w-[650px]">
    <BasicForm />
  </BasicModal>
</template>
